package com.AdvancedDemos.FileAndIO;

import java.io.*;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.function.IntFunction;

public class 练习2王嘉伟字节流实现 {
    public static void main(String[] args) throws IOException {
        //生成10个[1,9]之间的随机数,存储到当前模块下的source.txt文件中,格式如下:
        //2 3 7 5 6 8 9 1 2 4
        //读取该数据,将数据排序后,重新存储到当前模块下的result.txt文件中

        write();
        BufferedReader br = new BufferedReader(new FileReader("helloworld\\src\\com\\AdvancedDemos\\FileAndIO\\source.txt"));
        String s = br.readLine();
        br.close();

        Integer[] integers = Arrays.stream(s.split(" ")).map(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.valueOf(s);
            }
        }).sorted()/*stream自然排序*/.toArray(new IntFunction<Integer[]>() {
            @Override
            public Integer[] apply(int value) {
                return new Integer[value];
            }
        });

        String result = Arrays.toString(integers).replace("[", "").replace("]", "").replace(", ", " ");
        System.out.println("排序后的数组为:" + result);//随机数为:9 8 6 8 5 1 4 5 8 8

        BufferedWriter bw = new BufferedWriter(new FileWriter("helloworld\\src\\com\\AdvancedDemos\\FileAndIO\\result.txt"));
        bw.write(result);
        bw.close();

    }

    private static void write() throws IOException {
        //1.生成随机数,并写入到文件中
        StringJoiner sj = new StringJoiner(" ", "", "");
        for (int i = 0; i < 10; i++) {
            sj.add((int) (Math.random() * 9) + 1 + "");
        }
        System.out.println("随机数为:" + sj.toString());//随机数为:9 8 6 8 5 1 4 5 8 8
        //写入到文件
        BufferedWriter bw = new BufferedWriter(new FileWriter("helloworld\\src\\com\\AdvancedDemos\\FileAndIO\\source.txt"));
        bw.write(sj.toString());
        bw.close();
    }
}
